//
//  WTPlayVisitorsView.m
//  WTPlayDemo
//
//  Created by ben on 16/7/15.
//  Copyright © 2016年 ben. All rights reserved.
//

#import "WTPlayVisitorsView.h"
#import "Masonry.h"
#import "WTLiveSDKHeaders.h"
#import "WTCategories.h"



@implementation WTPlayVisitorCell
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.iconImageView = [[UIImageView alloc] init];
        self.iconImageView.layer.cornerRadius = 15;
        self.iconImageView.layer.masksToBounds = YES;
        [self.contentView addSubview:self.iconImageView];
        self.iconImageView.image = [UIImage wt_imageWithName:@"wt_avatar"];
        [self.iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self);
        }];
    }
    return self;
}

@end


@interface WTPlayVisitorsView ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, strong) UICollectionView* visitorsCollectionView;
@property (nonatomic, assign)  BOOL   isLoading;
@property (nonatomic, strong)  NSArray<NIMChatroomMember *> *members;
@property (nonatomic, strong)  NIMChatroomMember*    lastMember;
@end


@implementation WTPlayVisitorsView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}



#pragma mark -
- (void)setup{
    
    self.visitorsCollectionView = ({
        
        UICollectionViewFlowLayout*  layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 4;
        layout.itemSize = CGSizeMake(30, 30);
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        UICollectionView* view = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
        view.alwaysBounceHorizontal = YES;
        
        [view registerClass:[WTPlayVisitorCell class] forCellWithReuseIdentifier:NSStringFromClass([WTPlayVisitorCell class])];
        view.backgroundColor = [UIColor clearColor];
        view.dataSource = self;
        view.delegate = self;
        view.showsHorizontalScrollIndicator = NO;
        [self addSubview:view];
        
        view;
    });
    
    [self layout];
}

#pragma mark -
- (void)layout{
    
    [self.visitorsCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self);
    }];
}


#pragma mark - 
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.members.count;
}

- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    WTPlayVisitorCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([WTPlayVisitorCell class]) forIndexPath:indexPath];
    NIMChatroomMember *member = self.members[indexPath.row];
    [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:member.roomAvatar] placeholderImage:[UIImage wt_imageWithName:@"wt_avatar"]];
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NIMChatroomMember *member = self.members[indexPath.row];
    if(self.memberBlock){
        self.memberBlock(member.userId);
    }
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGPoint offset = scrollView.contentOffset;
    CGRect bounds = scrollView.bounds;
    CGSize size = scrollView.contentSize;
    UIEdgeInsets inset = scrollView.contentInset;
    float y = offset.x + bounds.size.width - inset.right;
    float h = size.width;
    
    
    float reload_distance = 30; //distance for which you want to load more
    if(y > h + reload_distance) {
        
        __weak __typeof(self)weakSelf = self;
        [self fetchMore:^(NSArray * datas) {
            
            NSMutableArray* tmp = [weakSelf.members mutableCopy];
            [tmp addObjectsFromArray:datas];
            weakSelf.members = [tmp copy];
            
            [weakSelf.visitorsCollectionView reloadData];
        } failure:^(NSError * error) {
            
        }];

    }
}

- (NSDictionary*)getExtInfoWithNet_ease_id:(NSString*)net_ease_id string:(NSString*)string{
    
    id  obj = [string mj_JSONObject];
    if(obj && [obj isKindOfClass:[NSArray class]]){
        
        for(NSDictionary* info in  obj){
            NSString* net_ease = info[@"net_ease_id"];
            if([net_ease isEqualToString:net_ease_id]){
                return info;
            }
        }
        
        return nil;
    }else {
        return obj;
    }
}

- (void)fetchMore:(void (^)(NSArray*))success failure:(void (^)(NSError *))failure{
    
    if(self.isLoading){
        return;
    }

    self.isLoading = YES;
    NIMChatroomMemberRequest *request = [[NIMChatroomMemberRequest alloc] init];
    request.roomId = [NSString stringWithFormat:@"%zd",self.roomId];
    request.type   = NIMChatroomFetchMemberTypeTemp;
    request.limit  = 50;
    request.lastMember = self.lastMember;
    __weak __typeof(self)weakSelf = self;
    [[NIMSDK sharedSDK].chatroomManager fetchChatroomMembers:request completion:^(NSError *error, NSArray *members) {
        
        if (!error){
            
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                __block NIMChatroomMember* roomOwner = nil;
                
                for(NIMChatroomMember* obj in members){
                    
                    if(obj.type == NIMChatroomMemberTypeCreator){
                        roomOwner = obj;
                    }
                    NSString*  memeberExtInfo = obj.roomExt;
                    
                    if(memeberExtInfo){
                        NSDictionary* info = [self getExtInfoWithNet_ease_id:obj.userId string:memeberExtInfo];
                        NSString* avatar = [info objectForKey:@"icon"];
                        obj.roomAvatar = avatar;
                        obj.roomExt = [NSString stringWithFormat:@"%zd",[info[@"level"] integerValue]];
                    }
                }
                
                if(members.count > 0){
                    weakSelf.lastMember = [members lastObject];
                }
                
                NSArray *sortArr = [members sortedArrayUsingComparator:^NSComparisonResult(NIMChatroomMember*  _Nonnull obj1, NIMChatroomMember*  _Nonnull obj2) {
                    
                    NSInteger level1 = [obj1.roomExt integerValue];
                    NSInteger level2 = [obj2.roomExt integerValue];
                    if(level1 > level2){
                        return NSOrderedAscending;
                    }else if(level1 < level2){
                        return NSOrderedAscending;
                    }else {
                        return NSOrderedSame;
                    }
                }];
                
                NSMutableArray* tmpMembers = [sortArr mutableCopy];
                if(roomOwner){
                    [tmpMembers removeObject:roomOwner];
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    success([tmpMembers copy]);
                    weakSelf.isLoading = NO;
                });
                
            });
        }
        else
        {
            weakSelf.isLoading = NO;
            failure(error);
        }
    }];
}

- (void)fetch{

    self.lastMember = nil;
    __weak __typeof(self)weakSelf = self;
    [self fetchMore:^(NSArray * datas) {
        weakSelf.members = datas;
        [weakSelf.visitorsCollectionView reloadData];
    } failure:^(NSError * error) {
        
    }];
}


@end
